<template>
  <div class="model-evaluation-chart">
    <div v-if="modelDetailData.length > 0" class="chart-content">
      <div class="chart-header">
        <div class="chart-title">{{ title }}</div>
        <el-button
          type="text"
          size="mini"
          class="export-btn"
          @click="exportChartImage"
        >
          导出图片
        </el-button>
      </div>
      <div
        ref="chartContainer"
        :style="{ width: '100%', height: chartHeight }"
      ></div>
    </div>
    <div v-else class="empty-chart-placeholder">
      <div class="chart-title">{{ title }}</div>
      <div class="placeholder-content">
        <i class="el-icon-info"></i>
        <p>请先完成模型训练步骤</p>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "ModelEvaluationChart",
  props: {
    title: {
      type: String,
      default: "模型评价曲线",
    },
    modelDetailData: {
      type: Array,
      default: () => [],
    },
    chartHeight: {
      type: String,
      default: "300px",
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    this.initChart();
    window.addEventListener("resize", this.handleResize);
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
    window.removeEventListener("resize", this.handleResize);
  },
  watch: {
    modelDetailData: {
      handler(newData, oldData) {
        if ((!oldData || oldData.length === 0) && newData.length > 0) {
          this.$nextTick(() => {
            if (this.chart) {
              this.chart.dispose();
              this.chart = null;
            }
            this.initChart();
          });
        } else {
          this.$nextTick(() => {
            this.updateChart();
          });
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    initChart() {
      if (this.$refs.chartContainer && this.modelDetailData.length > 0) {
        this.chart = echarts.init(this.$refs.chartContainer);
        this.updateChart();
      }
    },

    updateChart() {
      if (!this.chart || !this.modelDetailData.length) return;

      const sortedData = [...this.modelDetailData].sort(
        (a, b) => (a.latentVariableCount || 0) - (b.latentVariableCount || 0)
      );

      const xAxisData = sortedData.map((item) => item.latentVariableCount || 0);
      const rc2Data = sortedData.map((item) => parseFloat(item.rc2) || 0);
      const rmsecvData = sortedData.map((item) => parseFloat(item.rmsecv) || 0);
      const rp2Data = sortedData.map((item) => parseFloat(item.rp2) || 0);
      const rmsepData = sortedData.map((item) => parseFloat(item.rmsep) || 0);
      const rpdData = sortedData.map((item) => parseFloat(item.rpd) || 0);
      const tValueData = sortedData.map((item) => parseFloat(item.t_value) || 0);

      const colors = {
        rc2: "#1890ff",
        rmsecv: "#52c41a",
        rp2: "#fa8c16",
        rmsep: "#eb2f96",
        rpd: "#722ed1",
        t_value: "#f5222d",
      };

      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "cross" },
          formatter: (params) => {
            let result = `潜在变量数: ${params[0].axisValue}<br/>`;
            params.forEach((param) => {
              result += `${param.seriesName}: ${param.value.toFixed(4)}<br/>`;
            });
            return result;
          },
        },
        legend: {
          data: ["Rc²", "RMSECV", "Rp²", "RMSEP", "RPD", "t检验"],
          top: 10,
          type: "scroll",
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "15%",
          top: "15%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: xAxisData,
          name: "潜在变量数",
          nameLocation: "middle",
          nameGap: 25,
        },
        yAxis: {
          type: "value",
          name: "评价指标值",
          nameLocation: "middle",
          nameGap: 50,
          scale: true,
        },
        series: [
          {
            name: "Rc²",
            type: "line",
            data: rc2Data,
            lineStyle: { color: colors.rc2, width: 2 },
            itemStyle: { color: colors.rc2 },
            symbol: "circle",
            symbolSize: 6,
          },
          {
            name: "RMSECV",
            type: "line",
            data: rmsecvData,
            lineStyle: { color: colors.rmsecv, width: 2 },
            itemStyle: { color: colors.rmsecv },
            symbol: "circle",
            symbolSize: 6,
          },
          {
            name: "Rp²",
            type: "line",
            data: rp2Data,
            lineStyle: { color: colors.rp2, width: 2 },
            itemStyle: { color: colors.rp2 },
            symbol: "circle",
            symbolSize: 6,
          },
          {
            name: "RMSEP",
            type: "line",
            data: rmsepData,
            lineStyle: { color: colors.rmsep, width: 2 },
            itemStyle: { color: colors.rmsep },
            symbol: "circle",
            symbolSize: 6,
          },
          {
            name: "RPD",
            type: "line",
            data: rpdData,
            lineStyle: { color: colors.rpd, width: 2 },
            itemStyle: { color: colors.rpd },
            symbol: "circle",
            symbolSize: 6,
          },
          {
            name: "t检验",
            type: "line",
            data: tValueData,
            lineStyle: { color: colors.t_value, width: 2 },
            itemStyle: { color: colors.t_value },
            symbol: "circle",
            symbolSize: 6,
          },
        ],
      };

      this.chart.setOption(option, true);
    },

    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },

    exportChartImage() {
      if (this.chart) {
        const img = this.chart.getDataURL({
          type: "png",
          pixelRatio: 2,
          backgroundColor: "#fff",
        });
        const link = document.createElement("a");
        link.href = img;
        link.download = `${this.title}.png`;
        link.click();
      }
    },
  },
};
</script>

<style scoped>
.model-evaluation-chart {
  width: 100%;
  height: 100%;
}

.chart-content {
  width: 100%;
  height: 100%;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.chart-title {
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.export-btn {
  position: absolute;
  right: 0;
  top: 0;
  transform: translateY(-50%);
  font-size: 12px;
  padding: 2px 8px;
  background-color: #409eff;
  border: none;
  border-radius: 4px;
  color: #fff;
  cursor: pointer;
}

.export-btn:hover {
  background-color: #66b1ff;
}

.empty-chart-placeholder {
  width: 100%;
  height: 300px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  background-color: #fafafa;
}

.empty-chart-placeholder .chart-title {
  text-align: center;
  font-size: 14px;
  font-weight: bold;
  padding: 10px;
  color: #333;
  border-bottom: 1px solid #ebeef5;
  background-color: #fff;
}

.empty-chart-placeholder .placeholder-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #909399;
}

.empty-chart-placeholder .placeholder-content i {
  font-size: 48px;
  margin-bottom: 16px;
  color: #c0c4cc;
}

.empty-chart-placeholder .placeholder-content p {
  margin: 0;
  font-size: 14px;
}
</style>
